package com.demon.activitychange.xposed;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;

import com.demon.activitychange.R;
import com.demon.activitychange.util.TraceUtil;

public class ServiceMain extends Service {
    public static final int NOTICE_ID = 100;
    private PowerManager.WakeLock mWakeLock; // 防止被休眠

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TraceUtil.le("Service启动");

        //如果API大于18，需要弹出一个可见通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Notification.Builder builder = new Notification.Builder(this);
            // builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle(getString(R.string.app_name));
            builder.setContentText(getString(R.string.app_name) + "正在运行中...");
            builder.setAutoCancel(false);
            builder.setOngoing(true);
            startForeground(NOTICE_ID, builder.build());
        } else {
            startForeground(NOTICE_ID, new Notification());
        }

        // 广播也再次注册一下。。。机型兼容。。。
        if (!ReceiverMain.mIsInit) {
            ReceiverMain.registerReceiver(ServiceMain.this);
        }
        // 防止被休眠
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.jhassist.dy:waketag");
        mWakeLock.acquire();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TraceUtil.le("Service被杀死");

        // 如果Service被杀死，干掉通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mManager.cancel(NOTICE_ID);
        }

        try {
            if (mWakeLock != null)
                mWakeLock.release();
            mWakeLock = null;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(this.getApplicationContext(), ServiceMain.class);
        this.startService(intent);
    }
}
